package com.example.demo;

import org.springframework.boot.autoconfigure.task.TaskExecutionAutoConfiguration;
import org.springframework.boot.autoconfigure.task.TaskExecutionProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.context.event.SimpleApplicationEventMulticaster;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

@Configuration
public class BeanConfiguration {

    @Bean(AbstractApplicationContext.APPLICATION_EVENT_MULTICASTER_BEAN_NAME)
    public ApplicationEventMulticaster customApplicationMulticaster(ThreadPoolTaskExecutor taskExecutor){
       SimpleApplicationEventMulticaster eventMulticaster = new SimpleApplicationEventMulticaster();
        eventMulticaster.setTaskExecutor(taskExecutor);
       return eventMulticaster;
    }

    @Bean(TaskExecutionAutoConfiguration.APPLICATION_TASK_EXECUTOR_BEAN_NAME)
    public ThreadPoolTaskExecutor customThreadPoolTaskExecutor(TaskExecutionProperties taskExecutionProperties) {
        TaskExecutionProperties.Pool pool = taskExecutionProperties.getPool();

        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setThreadNamePrefix("myThread:");
        taskExecutor.setMaxPoolSize(pool.getMaxSize());
        taskExecutor.setCorePoolSize(pool.getCoreSize());
        taskExecutor.setKeepAliveSeconds(((Long) (pool.getKeepAlive().getSeconds())).intValue());
        taskExecutor.setQueueCapacity(pool.getQueueCapacity());
        return taskExecutor;
    }

}
